﻿using AJWPFAdmin.Core.Components.AJTable.ViewModels;
using AJWPFAdmin.Core.Enums;
using AJWPFAdmin.Core.Utils;
using AJWPFAdmin.Services.EF;
using MaterialDesignExtensions.Controls;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static AJWPFAdmin.Core.ExceptionTool;
using System.Windows.Controls;
using Masuit.Tools.Models;
using EntranceGuardManager.Modules.Main.Views;
using AJWPFAdmin.Core.Models.EF.Tables;
using AJWPFAdmin.Core.Mvvm;
using Microsoft.EntityFrameworkCore;
using Quartz.Util;
using System.IO;
using System.Windows;
using System.Diagnostics;
using AJWPFAdmin.Core.Models;
using AJWPFAdmin.Services.Models;

namespace EntranceGuardManager.Modules.Main.ViewModels
{
    public class ManualPassRecordListViewModel : ViewModelBase, INavigationAware
    {
        private AJTableFetchOptions _fetchOptions;

        public AJTableFetchOptions FetchOptions
        {
            get
            {
                return _fetchOptions;
            }
            set
            {
                SetProperty(ref _fetchOptions, value);
            }
        }

        private List<AJTableColumnItem> _columns;

        public List<AJTableColumnItem> Columns
        {
            get { return _columns; }
            set { SetProperty(ref _columns, value); }
        }

        private AJTableSearchFormConfig _formConfig;

        public AJTableSearchFormConfig FormConfig
        {
            get { return _formConfig; }
            set { SetProperty(ref _formConfig, value); }
        }

        private DelegateCommand<DataGridRow> _loadingRowCmd;
        public DelegateCommand<DataGridRow> LoadingRowCmd =>
            _loadingRowCmd ?? (_loadingRowCmd = new DelegateCommand<DataGridRow>(ExecuteLoadingRowCmd));

        void ExecuteLoadingRowCmd(DataGridRow row)
        {

        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _watchHouseOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> WatchHouseOptions
        {
            get { return _watchHouseOptions; }
            set
            {
                SetProperty(ref _watchHouseOptions, value);
            }
        }

        private ObservableCollection<AJTableFormSchemaItemOptions> _passagewayOptions;
        public ObservableCollection<AJTableFormSchemaItemOptions> PassagewayOptions
        {
            get { return _passagewayOptions; }
            set
            {
                SetProperty(ref _passagewayOptions, value);
            }
        }

        private DelegateCommand<ManualPassRecord> _openVideoStoreDirectoryCmd;
        public DelegateCommand<ManualPassRecord> OpenVideoStoreDirectoryCmd =>
            _openVideoStoreDirectoryCmd ?? (_openVideoStoreDirectoryCmd = new DelegateCommand<ManualPassRecord>(ExecuteOpenVideoStoreDirectoryCmd));

        void ExecuteOpenVideoStoreDirectoryCmd(ManualPassRecord parameter)
        {
            parameter.ComputeVideoCaptureDir(_carIdentificationConfig);

            if (string.IsNullOrWhiteSpace(parameter.VideoStoreDirectory)
                || !Directory.Exists(parameter.VideoStoreDirectory))
            {
                MessageBox.Show($"视频录像路径无效:{parameter.VideoStoreDirectory}", "提示", MessageBoxButton.OK);
                return;
            }

            CommonUtil.CreateCommand("explorer.exe", parameter.VideoStoreDirectory).Start();
        }

        private DbService db;
        private CarIdentificationConfig _carIdentificationConfig;

        public ManualPassRecordListViewModel(DbService dbIns, IEventAggregator eventAggregator)
        {
            //eventAggregator.GetEvent<AJGlobalExceptionResolvedEvent>().Subscribe(() => Loading = false);

            FetchOptions = new AJTableFetchOptions
            {
                //ExportFileName = "车辆记录导出",
                Handle = async (formCfg, pageCfg) =>
                {
                    var devCodeFormSchema = FormConfig.Schemas.FirstOrDefault(p => p.Field == nameof(ManualPassRecord.DeviceCode));

                    var devCode = devCodeFormSchema.Value == null ? string.Empty
                        : devCodeFormSchema.Value.ToString();

                    var houseFormSchema = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(ManualPassRecord.WatchhouseId));

                    var houseId = houseFormSchema.Value == null ? new long?() : (long)houseFormSchema.Value;

                    var passagewayFormSchema = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(ManualPassRecord.PassagewayId));

                    var passagewayId = passagewayFormSchema.Value == null
                        ? new long?() : (long)passagewayFormSchema.Value;

                    var dates = FormConfig.Schemas
                        .FirstOrDefault(p => p.Field == nameof(ManualPassRecord.CreateDate)).Value as ObservableCollection<DateTime?>;

                    if ((WatchHouseOptions?.Count).GetValueOrDefault() == 0)
                    {
                        var watchhouseOptions = await db.Watchhouses.AsNoTracking()
                        .Select(p => new AJTableFormSchemaItemOptions
                        {
                            Value = p.Id,
                            Label = p.Name
                        }).ToListAsync();

                        WatchHouseOptions = houseFormSchema.Options
                        = new ObservableCollection<AJTableFormSchemaItemOptions>(watchhouseOptions);
                    }

                    if ((PassagewayOptions?.Count).GetValueOrDefault() == 0)
                    {
                        var passagewayOptions = await db.Passageways.AsNoTracking()
                        .Select(p => new AJTableFormSchemaItemOptions
                        {
                            Value = p.Id,
                            Label = p.Name,
                            OtherData = p.WatchhouseId
                        }).ToListAsync();

                        PassagewayOptions = passagewayFormSchema.Options
                            = new ObservableCollection<AJTableFormSchemaItemOptions>(passagewayOptions);
                    }

                    var list = await db.ManualPassRecords
                        .LikeOrLike(devCode, p => p.DeviceCode)
                        .IfWhere(() => houseId.HasValue, p => p.WatchhouseId == houseId)
                        .IfWhere(() => passagewayId.HasValue, p => p.PassagewayId == passagewayId)
                        .BetweenInDates(dates.ToArray(), p => p.CreateDate)
                        .OrderByDescending(p => p.CreateDate)
                        .ToPagedListAsync(pageCfg.Current, pageCfg.PageSize);

                    //list.Data.Add(new ManualPassRecord
                    //{
                    //    VideoStoreDirectory = "D:\\npmDev"
                    //});

                    return new AJTableFetchResult
                    {
                        Total = 1,// list.TotalCount,
                        HasNext = false,// list.HasNext,
                        Rows = list.Data
                    };
                }
            };

            FormConfig = new AJTableSearchFormConfig
            {
                Schemas = new ObservableCollection<AJTableSearchFormSchema>
                {
                    new AJTableSearchFormSchema
                    {
                        Label = "出入口",
                        Field = nameof(ManualPassRecord.WatchhouseId),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "道闸",
                        Field = nameof(ManualPassRecord.PassagewayId),
                        Type = AJTableSchemaType.Select,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Label = "设备编号",
                        Field = nameof(ManualPassRecord.DeviceCode),
                        Type = AJTableSchemaType.Input,
                        IsPopular = true,
                    },
                    new AJTableSearchFormSchema
                    {
                        Labels = new string[]{ "创建开始日期","创建结束日期" },
                        Field = nameof(ManualPassRecord.CreateDate),
                        Type = AJTableSchemaType.RangePicker,
                        Value = new ObservableCollection<DateTime?>( new DateTime?[2]{null,null}),
                        IsPopular = true,
                    },
                },
                AdvFilterVisibility = System.Windows.Visibility.Collapsed,
                ExportVisibility = System.Windows.Visibility.Collapsed,
            };

            Columns = new List<AJTableColumnItem>
            {
                new AJTableColumnItem
                {
                    Title = "操作",
                    CustomTemplate = new AJTableCustomTemplate
                    {
                        Key = "TableOperatioin"
                    },
                    Fixed = AJTableColumnFixedType.Right,
                    Width = new DataGridLength(160),
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.WatchhouseName),
                    Title = "岗亭名称"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.WatchhouseCode),
                    Title = "岗亭编号"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.PassagewayName),
                    Title = "道闸名称"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.PassagewayCode),
                    Title = "道闸编号"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.Direction),
                    Title = "进出方向"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.DeviceCode),
                    Title = "设备编号"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.DeviceName),
                    Title = "设备名称"
                },
                new AJTableColumnItem
                {
                    DataIndex = nameof(ManualPassRecord.CreateDate),
                    Title = "创建日期",
                    Formatter = new AJTableColumnFormatter
                    {
                        Handler = (val) =>
                        {
                            return ((DateTime)val).ToString("yyyy-MM-dd HH:mm:ss");
                        }
                    }
                }
            };
            db = dbIns;
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //ExecuteGetListCmd();
            _carIdentificationConfig = CarIdentificationConfigExt.GetCarIdentificationConfig(db);
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}
